package com.goods.business.service.imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.goods.business.mapper.*;
import com.goods.business.service.InStockService;
import com.goods.common.model.business.*;
import com.goods.common.vo.business.InStockDetailVO;
import com.goods.common.vo.business.InStockItemVO;
import com.goods.common.vo.business.InStockVO;
import com.goods.common.vo.business.SupplierVO;
import com.goods.common.vo.system.PageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liangliang
 * @Date 2021/11/8 14:12 Administrator
 * @Description
 */
@Service
public class InStockServiceImpl implements InStockService {
    @Autowired
    private InStockMapper inStockMapper;
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private ProductStockMapper productStockMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private InStockInfoMapper inStockInfoMapper;

    /**
     * 查询入库记录
     *
     * @param
     * @param
     * @param
     * @param
     * @return
     */
    @Override
    public PageVO<InStockVO> findInStockList(Map map) {
        int pageNum = Integer.parseInt(map.get("pageNum").toString());
        int pageSize = Integer.parseInt(map.get("pageSize").toString());
        List<InStock> inStockList = inStockMapper.findByInStock(map);
        System.out.println("inStockList = " + inStockList);
        if (!CollectionUtils.isEmpty(inStockList)) {
            List<InStockVO> inStockVOList = inStockList.stream().map(inStock -> {
                Long supplierId = inStock.getSupplierId();
                List<Supplier> supplierList = supplierMapper.supplierListById(supplierId);
                InStockVO inStockVO1 = new InStockVO();
                supplierList.stream().forEach(supplier -> {
                    inStockVO1.setSupplierName(supplier.getName());
                    BeanUtils.copyProperties(inStock, inStockVO1);
                });

                return inStockVO1;
            }).collect(Collectors.toList());
            //获取总记录数
            int total = inStockVOList.size();
            //从第几条数据开始
            int size = (pageNum - 1) * pageSize + pageSize;
            //每页显示的记录数
            List<InStockVO> inStockVOList1 = inStockVOList.subList((pageNum - 1) * pageSize, size > total ? total : size);
            PageVO<InStockVO> pageVO = new PageVO<>(total, inStockVOList1);
            return pageVO;
        }
        return null;
    }

    /**
     * 查询入库明细
     *
     * @param id
     * @param pageNum
     * @param
     * @return
     */
    @Override
    public InStockDetailVO findDetail(Long id, Integer pageNum) {
        InStockDetailVO inStockDetailVO = new InStockDetailVO();
        //①先根据ID查询spplier表封装spulierVo数据
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(inStock, inStockDetailVO);
        Supplier supplier2 = supplierMapper.selectByPrimaryKey(inStock.getSupplierId());
        SupplierVO supplierVO = new SupplierVO();
        BeanUtils.copyProperties(supplier2, supplierVO);
        inStockDetailVO.setSupplierVO(supplierVO);
        //②封装商品库存
        InStockInfo inStockInfo = new InStockInfo();
        inStockInfo.setInNum(inStock.getInNum());
        List<InStockInfo> inStockInfoList = inStockInfoMapper.select(inStockInfo);
        List<InStockItemVO> itemVOS = inStockDetailVO.getItemVOS();
        inStockInfoList.stream().forEach(inStockInfo1 -> {
            String pNum = inStockInfo1.getPNum();

            ProductStock productStock = productStockMapper.selectBypNum(pNum);//一个pum遍历出一个productStock
            if (productStock!=null){
                String productPNum = productStock.getPNum();
                Product product = new Product();
                product.setPNum(productPNum);
                Product product1 = productMapper.selectOne(product);
                if (product1 != null) {
                    InStockItemVO inStockItemVO = new InStockItemVO();
                    BeanUtils.copyProperties(product1, inStockItemVO);
                    itemVOS.add(inStockItemVO);
                }
            }


        });
        inStockDetailVO.setItemVOS(itemVOS);
        int total = itemVOS.size();
        inStockDetailVO.setTotal(total);
        return inStockDetailVO;


    }

    /**
     * 将已经入库的移入回收站
     *
     * @param id
     */
    @Override
    public void remove(Long id) {
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        inStock.setStatus(1);
        inStockMapper.updateByPrimaryKey(inStock);
    }

    /**
     * 还原回收站中的数据
     *
     * @param id
     */
    @Override
    public void back(Long id) {
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        inStock.setStatus(0);
        inStockMapper.updateByPrimaryKey(inStock);
    }

    /**
     * 删除回收站中的数据
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        inStockMapper.deleteByPrimaryKey(id);
    }

    /**
     * 审核通过
     *
     * @param id
     */
    @Override
    public void publish(Long id) {
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        inStock.setStatus(0);
        inStockMapper.updateByPrimaryKey(inStock);
    }

    /**
     * 添加库存
     *
     * @param
     */
    @Override
    public void addIntoStock(InStockVO inStockVO) {
        //先根据supplierId判断是已知来源还是未知来源
        //1.先判断SupplierId是否为null；
        // 是 ： 先添加,直接往下走
        // 不是：再往下走 （需要id）
        Supplier supplier = new Supplier();
        if (inStockVO.getSupplierId() == null) {
            //先保存biz_supplier表
            BeanUtils.copyProperties(inStockVO, supplier);
            supplier.setModifiedTime(new Date());
            supplier.setCreateTime(new Date());
            supplier.setSort(inStockVO.getSort());
            supplierMapper.insert(supplier);
            //保存的是新增来源的数据
        }

        //保存biz_in_stock表
        InStock inStockS = new InStock();
        String in_numS = UUID.randomUUID().toString();
        inStockS.setInNum(in_numS);
        inStockS.setType(inStockVO.getType());
        inStockS.setOperator(inStockVO.getOperator());
        inStockS.setCreateTime(new Date());
        inStockS.setModified(new Date());
        inStockS.setSupplierId(supplier.getId());
        List<Object> productL = inStockVO.getProducts();
        int number=0;
        for (Object product : productL) {
            String s = JSONObject.toJSONString(product);
            Map map = JSON.parseObject(s, Map.class);
            Integer productId = (Integer) map.get("productId");
            Integer productNumber = (Integer) map.get("productNumber");
            number+=productNumber;
            //保存biz_in_stock_info表
            Product product1 = productMapper.selectByPrimaryKey(productId);
            InStockInfo inStockInfo1 = new InStockInfo();
            inStockInfo1.setPNum(product1.getPNum());
            inStockInfo1.setInNum(in_numS);
            inStockInfo1.setProductNumber(productNumber);
            inStockInfo1.setCreateTime(new Date());
            inStockInfo1.setModifiedTime(new Date());
            inStockInfoMapper.insert(inStockInfo1);
        }
        inStockS.setProductNumber(number);
        inStockS.setRemark(inStockVO.getRemark());
        inStockS.setStatus(2);
        inStockMapper.insert(inStockS);



      /*  //保存的是已知来源数据
        //保存biz_in_stock表
        InStock inStock = new InStock();
        String in_num = UUID.randomUUID().toString();
        inStock.setInNum(in_num);
        inStock.setType(inStockVO.getType());
        inStock.setOperator(inStockVO.getOperator());
        inStock.setCreateTime(new Date());
        inStock.setModified(new Date());
        List<Object> products = inStockVO.getProducts();
        for (Object product : products) {
            String s = JSONObject.toJSONString(product);
            Map map = JSON.parseObject(s, Map.class);
            Integer productId = (Integer) map.get("productId");
            Integer productNumber = (Integer) map.get("productNumber");
            inStock.setProductNumber(productNumber);
            inStock.setSupplierId(inStockVO.getSupplierId());
            inStock.setRemark(inStockVO.getRemark());
            inStock.setStatus(2);
            inStockMapper.insert(inStock);


            //保存biz_in_stock_info表
            Product product1 = productMapper.selectByPrimaryKey(productId);
            InStockInfo inStockInfo1 = new InStockInfo();
            inStockInfo1.setPNum(product1.getPNum());
            inStockInfo1.setInNum(in_num);
            inStockInfo1.setProductNumber(productNumber);
            inStockInfo1.setCreateTime(new Date());
            inStockInfo1.setModifiedTime(new Date());
            inStockInfoMapper.insert(inStockInfo1);*/

        }

    }

